#include "pthread.hpp"

using namespace Thread;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;


void* SlaverCore(void* args)
{
    string name = static_cast<char*>(args);

    while(1)
    {
        //加锁
        pthread_mutex_lock(&gmutex);
        cout<< "创建slaver成功: "<<name<<endl;
        //访问共享资源

        //去到等待队列
        pthread_cond_wait(&gcond,&gmutex);
        cout<< "现在被唤醒的线程是："<<name<<endl;
        //解锁
        pthread_mutex_unlock(&gmutex);
    }
}


void* MasterCore(void* args)
{
    sleep(2);
    string name = static_cast<char*>(args);
    while(1)
    {
        pthread_cond_signal(&gcond);
        cout<<"master 唤醒一个线程"<<endl;
        sleep(1);
    }
}


void StartSlaver(vector<pthread_t>* threads,int num)
{
    for(int i = 0;i<num;i++)
    {
        pthread_t tid;
        char* ch = new char[64];
        snprintf(ch,64,"thread-slaver-%d",i+1);
        int n = pthread_create(&tid,nullptr,SlaverCore,ch);
        if(n == 0)
            cout<<"Start Slaver Success"<<endl;
        threads->emplace_back(tid);
    }
}


void StartMaster(vector<pthread_t>* threads)
{
    pthread_t tid;
    int n = pthread_create(&tid,nullptr,MasterCore,(void*)"thread-master");
    if(n == 0)
        cout<<"Start Master Success"<<endl;
    threads->emplace_back(tid);
}


void Waitphread(vector<pthread_t>& threads)
{
    for(auto& thread : threads)
    {
        pthread_join(thread,nullptr);
    }
}

int main()
{
    vector<pthread_t> threads;
    StartMaster(&threads);
    StartSlaver(&threads,3);
    Waitphread(threads);
}